package code;

public class ListAdd_day06 {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode p1=l1;
        ListNode p2=l2;
        ListNode num=new ListNode((p1.val+p2.val)%10);
        int carry=(l1.val+l2.val)/10;
        ListNode p=num;
        p1=p1.next;
        p2=p2.next;
        while(p1!=null &&p2!=null){
            if(p1.val+p2.val+carry<10){
                p.next=new ListNode(p1.val+p2.val+carry);
                carry=0;
            }else {
                p.next=new ListNode((p1.val+p2.val+carry)%10);
                carry=1;
            }
            p=p.next;
            p1=p1.next;
            p2=p2.next;
        }
        while(p1!=null){
            p.next=new ListNode(p1.val);
            p=p.next;
            p1=p1.next;
        }
        while(p2!=null){
            p.next=new ListNode(p2.val);
            p=p.next;
            p2=p2.next;
        }
        if(carry==1){
            p.next=new ListNode(1);
        }
        return num;

    }
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public static void main(String[] args) {
        ListNode head1 = new ListNode(2);head1.next = null;
        ListNode temp1= new ListNode(4);head1.next = temp1;
        ListNode temp2= new ListNode(3);temp1.next = temp2;
        ListNode head2 = new ListNode(5);head2.next = null;
        ListNode temp4= new ListNode(6);head2.next = temp4;
        ListNode temp5= new ListNode(4);temp4.next = temp5;
        ListNode head= addTwoNumbers(head1,head2) ;
        ListNode p=head;
        while (p != null) {
            System.out.println(p.val);
            p=p.next;
        }
    }
}
